package com.zm.xiaohashu.biz.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import com.zm.exception.BizException;
import com.zm.response.Response;
import com.zm.xiaohashu.biz.constant.RedisConstant;
import com.zm.xiaohashu.biz.enums.ResponseCodeEnum;
import com.zm.xiaohashu.biz.service.NoteContentService;
import com.zm.xiaohashu.model.req.AddNoteContentReqDTO;
import com.zm.xiaohashu.model.req.DeleteNoteContentReqDTO;
import com.zm.xiaohashu.model.req.FindNoteContentReqDTO;
import com.zm.xiaohashu.model.resp.FindNoteContentRspDTO;
import com.zm.xiaohashu.model.vo.NoteContentDO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.UUID;

@Slf4j
@Service
public class NoteContentServiceImpl implements NoteContentService {
    @Resource(name = "stringRedisTemplate")
    private StringRedisTemplate redisTemplate;

    @Override
    public Response<?> addNoteContent(AddNoteContentReqDTO addNoteContentReqDTO) {
        String content = addNoteContentReqDTO.getContent();
        String noteId = addNoteContentReqDTO.getUuid();
        // 构建数据库 DO 实体类
        String redisKey = RedisConstant.NOTE_CONTENT_KEY + noteId;
        String NoteContext = JSONUtil.toJsonStr(content);
        redisTemplate.opsForValue().set(redisKey, NoteContext);
        return Response.success();
    }

    @Override
    public Response<FindNoteContentRspDTO> findNoteContent(FindNoteContentReqDTO findNoteContentReqDTO) {
        String noteId = findNoteContentReqDTO.getUuid();
        String redisKey = RedisConstant.NOTE_CONTENT_KEY + noteId;
        String noteContent = redisTemplate.opsForValue().get(redisKey);
        if (Objects.isNull(noteContent)) {
            throw new BizException(ResponseCodeEnum.NOTE_CONTENT_NOT_FOUND);
        }
        FindNoteContentRspDTO findNoteContentRspDTO = FindNoteContentRspDTO.builder()
                .content(noteContent)
                .uuid(UUID.fromString(noteId))
                .build();
        return Response.success(findNoteContentRspDTO);
    }

    @Override
    public Response<?> deleteNoteContent(DeleteNoteContentReqDTO deleteNoteContentReqDTO) {
        String noteId = deleteNoteContentReqDTO.getUuid();
        redisTemplate.delete(RedisConstant.NOTE_CONTENT_KEY + noteId);
        return Response.success();
    }
}
